import os
from django.core.wsgi import get_wsgi_application
from django.contrib.staticfiles.handlers import StaticFilesHandler
from waitress import serve
import socket

def get_local_ip():
    try:
        # 创建一个临时 socket 连接以获取本地 IP
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))  # 连接到 Google 的 DNS 服务器
        local_ip = s.getsockname()[0]
        s.close()
        return local_ip
    except Exception:
        return "127.0.0.1"  # 如果无法获取，则回退到本地回环地址



# 设置 Django 环境变量
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')

# 使用 StaticFilesHandler 包装应用程序
application = StaticFilesHandler(get_wsgi_application())

# 打印访问地址信息
print("Starting server on http://0.0.0.0:8000")
print("You can access your application at:")
print("  - http://localhost:8000")
print("  - http://127.0.0.1:8000")
print("    If running on a network, you may access it via :")
# 在打印信息中使用
print(f"  - http://{get_local_ip()}:8000")

# 启动 Waitress 服务器
serve(application, host="0.0.0.0", port=8000, threads=4)

#运行时：python runserver.py